<template>
  <div class="chart-container" ref="chart">
    <!-- 装饰性元素保持不变 -->
    <div class="corner-decor corner-tl"></div>
    <div class="corner-decor corner-tr"></div>
    <div class="corner-decor corner-bl"></div>
    <div class="corner-decor corner-br"></div>
    <div class="glow-effect"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import {onMounted, onUnmounted, ref, watch} from 'vue'
import {useResize} from '~/utils/resize'

export default {
  props: {
    data: {
      type: Array,
      required: true,
      default: () => []
    },
    title: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    const chart = ref(null)
    let myChart = null
    let animationInterval = null

// 专业渐变配色方案
    const colorPalette = [
      {color: 'rgba(79,216,222,0.8)', hover: 'rgba(79,216,222,1)'},
      {color: 'rgba(11,93,232,0.8)', hover: 'rgba(11,93,232,1)'},
      {color: 'rgba(82,196,26,0.8)', hover: 'rgba(82,196,26,1)'},
      {color: 'rgba(245,34,45,0.8)', hover: 'rgba(245,34,45,1)'},
      {color: 'rgba(250,173,20,0.8)', hover: 'rgba(250,173,20,1)'},
      {color: 'rgba(114,46,209,0.8)', hover: 'rgba(114,46,209,1)'},
      {color: 'rgba(19,194,194,0.8)', hover: 'rgba(19,194,194,1)'},
      {color: 'rgba(235,47,150,0.8)', hover: 'rgba(235,47,150,1)'}
    ]

// 3D光效配置
    const lightConfig = {
      main: {
        alpha: 55,
        beta: 10,
        intensity: 1.2
      },
      ambient: {
        intensity: 0.3
      }
    }

    const initChart = () => {
      if (!chart.value) return

      myChart = echarts.init(chart.value)
// 添加此事件处理防止tooltip重叠
      myChart.on('mouseover', {seriesIndex: 0}, (params) => {
// 取消之前所有的高亮状态
        myChart.dispatchAction({
          type: 'downplay',
          seriesIndex: 0
        })

// 高亮当前项
        myChart.dispatchAction({
          type: 'highlight',
          seriesIndex: 0,
          dataIndex: params.dataIndex
        })

// 只显示当前tooltip
        myChart.dispatchAction({
          type: 'showTip',
          seriesIndex: 0,
          dataIndex: params.dataIndex
        })
      })

      updateChart()
      startAutoRotation()
    }

    const updateChart = () => {
// 根据数据项数量动态调整布局
      const legendRight = props.data.length > 5 ? '10%' : '5%'
      const pieCenterLeft = props.data.length > 5 ? '35%' : '40%'
      const pieRadius = props.data.length > 5 ? ['50%', '75%'] : ['60%', '85%']

      const option = {
        title: {
          text: props.title,
          left: 'center',
          top: 15,
          textStyle: {
            color: '#fff',
            fontSize: 18,
            fontWeight: 'bold',
            fontFamily: 'Microsoft YaHei',
            textShadow: '0 0 10px rgba(79, 216, 222, 0.7)'
          }
        },
        tooltip: {
          trigger: 'item',
          confine: true,
          alwaysShowContent: false,
          enterable: true,
          backgroundColor: 'rgba(13, 42, 67, 0.95)',
          borderColor: '#4fd8de',
          borderWidth: 1,
          padding: [10, 15],
          textStyle: {
            color: '#fff',
            fontSize: 14,
            lineHeight: 24
          },
          extraCssText: 'box-shadow: 0 0 20px rgba(79, 216, 222, 0.5);',
          formatter: params => {
            return `
<div style="font-size:16px;font-weight:bold;margin-bottom:8px;color:#4fd8de">${params.name}</div>
<div style="display:flex;align-items:center;margin:5px 0">
<span style="display:inline-block;width:12px;height:12px;background:${params.color};border-radius:2px;margin-right:8px"></span>
<span style="flex:1">数量：</span>
<strong style="color:#fff">${params.value}</strong>
</div>
<div style="display:flex;align-items:center;margin:5px 0">
<span style="display:inline-block;width:12px;height:12px;opacity:0;margin-right:8px"></span>
<span style="flex:1">占比：</span>
<strong style="color:#fff">${params.percent}%</strong>
</div>
`
          }
        },
        legend: {
          orient: 'vertical',
          right: legendRight,
          top: 'center',
          textStyle: {
            color: '#fff',
            fontSize: 12,
            rich: {
              name: {
                width: props.data.length > 5 ? 80 : 100, // 根据数据量调整宽度
                overflow: 'truncate',
                ellipsis: '...'
              },
              value: {
                color: '#4fd8de',
                fontWeight: 'bold',
                padding: [0, 0, 0, 10]
              }
            }
          },
          itemWidth: 12,
          itemHeight: 12,
          itemGap: 15, // 减少项间距
          icon: 'circle',
          formatter: name => {
            const item = props.data.find(d => d.name === name)
            return `{name|${name}}{value|${item ? item.value : ''}}`
          },
// 添加滚动功能防止过多项溢出
          type: 'scroll',
          pageIconColor: '#4fd8de',
          pageIconInactiveColor: '#666',
          pageTextStyle: {
            color: '#fff'
          }
        },
        series: [{
          name: '数据分布',
          type: 'pie',
          radius: pieRadius,
          center: [pieCenterLeft, '55%'],
          avoidLabelOverlap: true,
          hoverAnimation: true,
          silent: false,
          itemStyle: {
            borderRadius: 6,
            borderColor: 'rgba(12, 54, 83, 0.8)',
            borderWidth: 2,
            shadowBlur: 15,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          },
          label: {
            show: false,
            position: 'center',
            formatter: '{b}\n{c} ({d}%)',
            fontSize: 14,
            color: '#fff',
            fontWeight: 'bold',
            textBorderColor: '#000',
            textBorderWidth: 2
          },
          emphasis: {
            scale: true,
            scaleSize: 15,
            label: {
              show: true,
              fontSize: 18,
              fontWeight: 'bold',
              color: '#fff'
            },
            itemStyle: {
              shadowBlur: 30,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.7)'
            }
          },
          labelLine: {
            show: false
          },
          data: props.data.map((item, index) => ({
            value: item.value,
            name: item.name,
            itemStyle: {
              color: {
                type: 'radial',
                x: 0.5,
                y: 0.5,
                r: 0.8,
                colorStops: [{
                  offset: 0,
                  color: colorPalette[index % colorPalette.length].color
                }, {
                  offset: 1,
                  color: colorPalette[index % colorPalette.length].hover
                }],
                global: false
              }
            }
          })),
          animationType: 'scale',
          animationEasing: 'elasticOut',
          animationDelay: function (idx) {
            return idx * 100
          },
          roseType: 'radius',
          selectedMode: 'single',
          selectedOffset: 10
        }],
        light: lightConfig
      }

      myChart.setOption(option)
    }

// 自动旋转动画
    const startAutoRotation = () => {
      let currentAngle = 0
      animationInterval = setInterval(() => {
        currentAngle += 0.5
        myChart.dispatchAction({
          type: 'pieRotate',
          angle: currentAngle
        })
      }, 100)
    }

// 高亮轮播
    const startHighlightCarousel = () => {
      let currentIndex = 0
      setInterval(() => {
        if (props.data.length === 0) return

        myChart.dispatchAction({
          type: 'downplay',
          seriesIndex: 0
        })

        myChart.dispatchAction({
          type: 'highlight',
          seriesIndex: 0,
          dataIndex: currentIndex % props.data.length
        })

        currentIndex++
      }, 3000)
    }

    onMounted(() => {
      initChart()
      useResize(myChart)
      startHighlightCarousel()
    })

    watch(() => props.data, () => {
      if (myChart) {
        updateChart()
      }
    }, {deep: true})

    onUnmounted(() => {
      if (animationInterval) {
        clearInterval(animationInterval)
      }
    })

    return {chart}
  }
}
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  min-height: 300px; /* 确保有足够高度 */
  background: rgba(13, 42, 67, 0.3);
  border-radius: 8px;
  box-shadow: 0 4px 30px rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(5px);
  border: 1px solid rgba(79, 216, 222, 0.2);
  position: relative;
  overflow: hidden;
}

/* 四角装饰元素 */
.corner-decor {
  position: absolute;
  width: 20px;
  height: 20px;
  border-color: #4fd8de;
  border-style: solid;
  border-width: 0;
  opacity: 0.6;
}

.corner-tl {
  top: 10px;
  left: 10px;
  border-top-width: 2px;
  border-left-width: 2px;
  border-radius: 6px 0 0 0;
}

.corner-tr {
  top: 10px;
  right: 10px;
  border-top-width: 2px;
  border-right-width: 2px;
  border-radius: 0 6px 0 0;
}

.corner-bl {
  bottom: 10px;
  left: 10px;
  border-bottom-width: 2px;
  border-left-width: 2px;
  border-radius: 0 0 0 6px;
}

.corner-br {
  bottom: 10px;
  right: 10px;
  border-bottom-width: 2px;
  border-right-width: 2px;
  border-radius: 0 0 6px 0;
}

/* 发光效果 */
.glow-effect {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border-radius: 8px;
  box-shadow: inset 0 0 50px rgba(79, 216, 222, 0.15);
  pointer-events: none;
  z-index: 0;
  animation: glowPulse 4s infinite alternate;
}

@keyframes glowPulse {
  0% {
    box-shadow: inset 0 0 30px rgba(79, 216, 222, 0.1);
  }
  100% {
    box-shadow: inset 0 0 60px rgba(79, 216, 222, 0.3);
  }
}
</style>